$(document).ready(function() {
	//things need to be hidden when DOM ready
	$('#optionsPanel').hide();
	$('#addedAgenciesWrapDiv').hide();

	/**Log in and log out control on menu bar (using localStorage)**/

	//Log in button
	$('#btnLogin').click(function(event) {
		if($('#ddlLoginType').val()==='0'){
			$.jGrowl("Please select log in agency",{life:10000});
			return false;
		}
			localStorage["username"] = $('#tbxUsername').val();
			localStorage["loginType"] = $('#ddlLoginType').val();
			window.location.href="inbox(1).html";
	});

	//on page display
	$('#username').text(localStorage["username"])
	$('#loginType').text(localStorage["loginType"])
	$('#btnLogout').click(function(event) {
		localStorage.removeItem("username");
		localStorage.removeitem("loginType");
		console.log("current username:");
		console.log(localStorage["username"]);
		console.log("current loginType:")
		console.log(localStorage["loginType"]);
	});

	//for case details page and update case page remove linked cases button
	$('.cancelLink').click(function(event) {
		$(this).parents('tr').remove();
	});
	

	$("#btnUpdate").click(function(event) {
		event.preventDefault();
		updateCaseInfo();	//this method is in dataExchange.js  
		$.jGrowl("Case updated!",{life:5000}) 
	});


	$('#btnReply').click(function(event) {
		$('#replyPanel-remarksDiv').hide();
		$('#replyPanel').toggle('drop');
		currTime = new Date();

		$('#replyPanel-datetime').empty();
		$('#replyPanel-datetime').append($.datepicker.formatDate("d-M-yy",new Date())+" "+currTime.getHours()+":"+currTime.getMinutes());
	});


	/**Accept and Reject case buttons on Case Details page**/
	$('#btnAccept').click(function(event) {
		$('#btnConfirmationDialogAccept').dialog( "open" );
	});
	$('#btnReject').click(function(event) {
		console.log($('#rejectComments').val());
		if($('#rejectComments').val()=="")
		{
			$('#emptyCommentsDialog').dialog('open');
			return false;
		}
		$('#btnConfirmationDialogReject').dialog( "open" );
	});


	$('#btnMoreOptions').click(function(event) {
		$('div#optionsPanel').toggle('drop');
		if($('#btnMoreOptions > i').hasClass('fa-chevron-up'))
		{
			$('#btnMoreOptions > i').removeClass('fa-chevron-up').addClass('fa-chevron-down');
		}else{
			$('#btnMoreOptions > i').removeClass('fa-chevron-down').addClass('fa-chevron-up');
		}
	});


	$('#replyPanel-btnAddRemarks').click(function(event) {
		if($('#replyPanel-btnAddRemarks > i').hasClass('fa-chevron-up'))
		{
			$('#replyPanel-btnAddRemarks > i').removeClass('fa-chevron-up').addClass('fa-chevron-down');
		}else{
			$('#replyPanel-btnAddRemarks > i').removeClass('fa-chevron-down').addClass('fa-chevron-up');
		}
	});


	$('#btnLinkCase').click(function(event) {
		var caseID = $('#caseIDTrunk').text();
		
		$("#linkCaseTable tr:gt(0)").each(function(){
			var th = $(this);
			if($(th).find("input[name='link-cbx']").is(":checked")){
				var id = $(th).find("td:eq(1)").text();
				var name = $(th).find("td:eq(7)").text();
				var type = $("input[name='linkType']:checked").val();
				if($("#detailInvolvedAgencyTable:contains('"+id+"')").length < 1){            
					$("#detailInvolvedAgencyTable").append('<tr><td>'+id+'</td><td>'+name+'</td><td style="position:relative;">'+type+'</td><td><i class="fa fa-times-circle fa-lg clickable cancelLink" title="Remove Link"></i></td></tr>');
					$('.cancelLink').click(function(event) {
						$(this).parents('tr').remove();
					});
				}
			}
		});
		$.jGrowl("Selected cases are linked with case " + caseID, {
			life: 10000
		});
	});


	/**Accept and Reject case buttons on Joint Resolution page**/
	$('#btnJointAccept').click(function(event) {
		if($('#responseDatepicker').val()==="")
		{
			$('#timeSelectorDialog').dialog('open');
			return false;
		}
		$('#btnJointConfirmationDialogAccept').dialog('open');
		
	});
	$('#btnJointReject').click(function(event) {
		console.log($('#rejectComments').val());
		if($('#rejectComments').val()==="")
		{
			$('#emptyCommentsDialog').dialog('open');
			return false;
		}
		$('#btnJointConfirmationDialogReject').dialog( "open" );
	});



	$('#btnApproveReply').click(function(event) {
		$('#btnApproveReply').hide('fade',function () {
			$('#btnApproveReplyTd').append('<span style="color:#037e37;">Approved</span>');
			$.jGrowl("You just approved this reply! ",{life:3000});
		});
	});


	$('#btnApproveCheck').click(function(event) {
		$( "#dialog-form" ).dialog( "open" );
	});


	$('#btnAddAgency').click(function(event) {
		$('#addedAgenciesWrapDiv').show('fast');

		var agencyName = $('#panelJoint-autoComp-agency').val();
		var isLead = $('#isLeadAgency').is(":checked") ? "(Lead)" : "";
		var title = $('#panelMulti-SubjectTitle').val();
		var category = $('#panelReroute-autoComp-category').val()===""?"":$('#panelReroute-autoComp-category').val();
		var subCategory = $('#panelReroute-autoComp-subCate').val()===""?"":$('#panelReroute-autoComp-subCate').val();

		$('#addedAgenciesTable tbody').append('<tr><td>'+title+'</td><td>'+category+'</td><td>'+subCategory+'</td><td>'+agencyName+isLead+'</td><td><i class="fa fa-times-circle fa-lg clickable btnAgencyRemover" title="Remove Link"></i></td></tr>');

		$('.btnAgencyRemover').click(function(event) {
			$(this).parents('tr').remove();
		});
	});


	$('#replyPanel-btnSubmitReply').click(function(event) {
		var datetime = $('#replyPanel-datetime').text();
		console.log("Datetime is: \n"+datetime);
		var channel = $('#replyPanel-channel').val();
		var agency = $('#replyPanel-agency').val();
		var officer = $('#replyPanel-officer').val();

		localStorage.response = $('#replyPanel-caseResponse').val();	//store full response text into localStorage
		console.log(localStorage.response);
		var trunkedResponse = localStorage.response.substring(0, 50)+" ...";
		var isFinal = $('#replyPanel-idFinal').is(':checked')?"Yes":"No";
		var isInformed = $('#replyPanel-isInformed').is(':checked')?"Yes":"No";

		$('#addResponseTable tbody').append('<tr><td class="hyperLinkText" title="Click to see details">'+ datetime +'</td><td>'+channel+'</td><td>'+agency+'</td><td>'+officer+'</td><td>'+trunkedResponse+'</td><td>'+isFinal+'</td></tr>');
	});


	$('#btnSendJointAgency').click(function(event) {
		$( "#sendConfirmationDialog" ).dialog( "open" );
	});




	$('.switch-button-button').click(function(event) {
		alert('haha');
		if($('#btnManageSwitch').is(':checked')){

			$('#involvedAgenciesTable').find('tr').each(function(index, el) {
				$(this).eq(0).before('<th>111</th>');
			});
		//$('#involvedAgenciesTable')
		}
	});


	/* manage involved agencies table on joint resolution page */
	$('#ddlSplitAgencyDiv').hide();    //Hide split joint combobox when page load

	var manageToggleStatus = 0;    //Toggle status of the manage options, 0 for closed, 1 for opened
	$('#btnManageAgenciesToggle').click(function(event) {

		console.log("toggle status: "+manageToggleStatus);
		if(manageToggleStatus===0){    //show manage options
			//Display radio buttons and comboboxes
			$('#manageAgenciesOptions').show();

			//Add a empty td to Lead Agency tr
			$('#involvedAgenciesTable > thead > tr > th:first-child').each(function(index, el) {
				//$(this).append('<input type="checkbox" class="cbxKickTick">');
				$(this).before('<th></th>');
			});

			//Add checkboxes onto table
			$('#involvedAgenciesTable > tbody > tr > td:first-child').each(function(index, el) {
				//$(this).append('<input type="checkbox" class="cbxKickTick">');
				if($(this).parents('tr').hasClass('notAddCbx')){
					$(this).before('<td></td>');
				}else{
					$(this).before('<td><input type="checkbox" class="cbxKickTick"/></td>');
				}
			});

			//bind click event to checkboxes added
			$('input.cbxKickTick').on("click", function() {    //this will add checked agency name into combobox
				var selectedAgency = $(this).parents('tr').find('td:eq(1)').text();
				if($(this).is(':checked')){
					if(selectedAgency !== ""){
						$('#ddlSplitLeadAgency option:contains("'+selectedAgency+'")').remove();
						$('#ddlSplitLeadAgency').append('<option value="'+selectedAgency+'">'+selectedAgency+'</option>')
					}
				}else{
					$('#ddlSplitLeadAgency option:contains("'+selectedAgency+'")').remove();
				}
			});
		}else{    //remove manage options
			$('#manageAgenciesOptions').hide();
			$('#involvedAgenciesTable > thead > tr > th:first-child').each(function(index, el) {
				$(this).remove();
			});
			$('#involvedAgenciesTable > tbody > tr > td:first-child').each(function(index, el) {
				$(this).remove();
			});
		}
		manageToggleStatus = manageToggleStatus===0?1:0;
	});

	//Delink radio button is clicked, hide split joint combobox
	$('#rbtnDelink').click(function(event) {
		$('#ddlSplitAgencyDiv').hide();    //hide split joint combobox
		$('#ddlSplitLeadAgency').empty();    //clear options in split joint combobox
		//$('#ddlChangeLeadAgencyDiv').hide();
		$('#involvedAgenciesTable > tbody > tr > td:first-child').each(function(index, el) {
			$(this).find('input').prop({
				type: 'checkbox',
				checked: false
			}).removeAttr('name');
			
		});

	});
	$('#rbtnSplit').click(function(event) {
		$('#ddlSplitLeadAgency').empty();    //clear options in split joint combobox
		$('#involvedAgenciesTable > tbody > tr > td:first-child').each(function(index, el) {
			$(this).find('input').prop({
				type: 'checkbox',
				checked: false
			}).removeAttr('name');
		});
		$('#ddlSplitAgencyDiv').show('fade');
	});
	$('#rbtnChangeLead').click(function(event) {
		$('#involvedAgenciesTable > tbody > tr > td:first-child').each(function(index, el) {
			$(this).find('input').prop('type', 'radio').attr('name', 'changeLeadRadio');
		});
		$('#ddlSplitAgencyDiv').hide();
	});


	$('#btnManageAgenciesExecute').click(function(event) {
		if($('#rbtnSplit').is(':checked')){
			$('#splidDialogLeadAgency').text($('#ddlSplitLeadAgency').val());
			$('#executeSplitDialog').dialog('open');
		}else if($('#rbtnChangeLead').is(':checked')){
			$('#changeLeadDialogLeadAgency').text($('input[name=changeLeadRadio]:checked').parents('tr').find('td:eq(1)').text());
			$('#executeChangeLeadDialog').dialog('open');
		}else{
			$('#executeDelinkDialog').dialog('open');
		}
	});


	$('#btnConfirmCreateNewCase').on("click",function(){
		createNewCase();
	});


	




});



function redirectEdit(){
	var _caseID = localStorage.caseID;
	document.location.href = "update-case(1).html";
}


